package operations;

import Book.Book;
import Book.BookList;

import java.util.Scanner;

public class DelOperation implements IOperation{
    public void work(BookList bookList){
        System.out.println("删除书籍");
        System.out.print("请输入你要删除的书籍：");
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        //1.遍历数组当中是否存在要删除的书 并记录下标
        int index = -1;
        int currentSize = bookList.getUsedsize();
        for (int i = 0; i < currentSize; i++) {
            if(name.equals(bookList.getPos(i).getName())){
                index = i;
                break;
            }
        }
        //
        if(index == -1){
            System.out.println("没有找到你要删除的书籍");
        }else{
            for (int i = index; i < currentSize-1; i++) {
                Book book = bookList.getPos(i+1);
                bookList.setBooks(book,i);
            }
            bookList.setBooks(null,currentSize-1);//将最后一个元素置为空，避免内存泄露
            bookList.setUsedsize(currentSize-1);//删除后更新书架中书的数目
            System.out.println("删除成功");
        }
    }
}
